﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using App.Utilities.Web.Handlers;
using System.Data;
using CRMBiz;
using Newtonsoft.Json;
using CRMEntity;
using CRMWeb.Utilities.Context;


namespace CRMWeb.WebServices
{
    /// <summary>
    /// Summary description for ApplicationContact
    /// </summary>
    public class ApplicationContact : BaseHandler
    {

        public override void OnMethodInvoke(OnMethodInvokeArgs e)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);
            context.Response.Cache.SetExpires(DateTime.MinValue);
            context.Response.Cache.SetNoStore();

            //e.Cancel = true;

            SetResponseContentType(ResponseContentTypes.HTML);
        }

        public override void AfterMethodInvoke(object result)
        {
            base.AfterMethodInvoke(result);
        }

        //user defined function
        #region private method

        public void ApplicationContactSelect(int ContactID)
        {
            try
            {
                string OperatorId = CMSContext.CurrentUser.NodeID.ToString();
                DataSet ds = ApplicationContactHandler.GetApplicationContact(ContactID, OperatorId);
                string strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
        }
        public void SelectClientDetail(int ContactID)
        {
            string OperatorId = CMSContext.CurrentUser.NodeID.ToString();
            bool isDuplicate = false;
            try
            {
                if (ContactID > 0)
                {
                    DataSet ds = ApplicationContactHandler.GetApplicationContact(ContactID, OperatorId);
                    if ((ds.Tables[0].Rows[0]["deletedFlag"].ToString() == "False") && (Convert.ToInt32(ds.Tables[0].Rows[0]["dupwith"].ToString()) <= 0))
                    {
                       
                        string bdate =ds.Tables[0].Rows[0]["DateBirth"].ToString();
                        string[] strdate = bdate.Split(' ');

                        isDuplicate = ApplicationContactHandler.CheckForDuplicate(ds.Tables[0].Rows[0]["FirstName"].ToString(), ds.Tables[0].Rows[0]["SurName"].ToString(), strdate[0]);
                    }
                    ds.Tables[0].Columns.Add("isDuplicate");
                    if (isDuplicate == true)
                        ds.Tables[0].Rows[0]["isDuplicate"] = "True";
                    else
                        ds.Tables[0].Rows[0]["isDuplicate"] = "False";

                    string strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                    context.Response.Write(strJson);
                }
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
        }
        public void GetApplicationForClient(int ContactID)
        {
            try
            {
                DataSet ds = ApplicationContactHandler.GetApplicationForClient(ContactID);
                string strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
        }
        public void ApplicationContactSelectAll()
        {
            try
            {
                var pageIndex = string.IsNullOrEmpty(context.Request["page"]) ? 1 : int.Parse(context.Request["page"]);
                var pageSize = string.IsNullOrEmpty(context.Request["rows"]) ? 10 : int.Parse(context.Request["rows"]);
                var searchtext = string.IsNullOrEmpty(context.Request.QueryString["searchtext"]) ? "" : context.Request.QueryString["searchtext"];
                var conditiontext = string.IsNullOrEmpty(context.Request.QueryString["conditiontext"]) ? "" : context.Request.QueryString["conditiontext"];
                var sortText = string.IsNullOrEmpty(context.Request.QueryString["sortCondition"]) ? "" : context.Request.QueryString["sortCondition"];
                var days = string.IsNullOrEmpty(context.Request.QueryString["days"]) ? "All" : context.Request.QueryString["days"];
                DataSet ds = ApplicationContactHandler.GetApplicationContactList(pageIndex, pageSize, searchtext, conditiontext, sortText, days);

                var total = (ds.Tables[0].Rows.Count > 0) ? Convert.ToInt32(ds.Tables[0].Rows[0]["Total"]) : 0;
                string strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                strJson = "{\"total\":\"" + total.ToString() + "\",\"rows\":" + strJson + "}";
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
        }
        public void GetAppLoanRecord(int ContactID, string sortText, int noInApp)
        {
            try
            {
                if (ContactID > 0)
                {
                    DataSet ds = ApplicationContactHandler.GetAppLoanRecord(ContactID, sortText, noInApp);
                    context.Response.Write(JsonConvert.SerializeObject(ds.Tables[0]));
                }
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
        }
        /// <summary>
        /// Get Application info by Contact Name  -- Wade 20140212
        /// </summary>
        /// <param name="app_id"></param>
        /// <param name="firstname"></param>
        /// <param name="middlename"></param>
        /// <param name="surname"></param>
        public void GetAppLoanRecordByName(int app_id,string firstname,string middlename,string surname)
        {
            try
            {
                DataSet ds = ApplicationContactHandler.GetAppLoanRecordByName(app_id, firstname, middlename, surname);
                context.Response.Write(JsonConvert.SerializeObject(ds.Tables[0]));
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
        }

        public void CheckContactID(int ContactID)
        {
            try
            {
                string strJson = string.Empty;
                bool flag = ApplicationContactHandler.CheckContactID(ContactID);
                if (flag == true)
                    strJson = "true";
                else
                    strJson = " false";
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
        }
        public void SelectApplicationByAppID(int app_id)
        {
            try
            {
                DataSet ds = ApplicationDetailHandler.SelectApplicationDetail(app_id);
                string strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
        }

        public void BindApplicationContactForm(int ContactID)
        {
            try
            {
                DataSet ds = ApplicationContactHandler.GetApplicationContactForm(ContactID);
                string strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
        }
        public void ApplicationContactAdd(string Title, string FirstName, string MiddleName, string SurName, string Citizenship, string DateBirth, string DriverLicense, string Mobile, string HomePhone,
            string Email, string secondEmailAddress, string StreetNo, string Street, string Suburb, string State, string PostCode,
            string app_ResidentialStatus, string ResidencePeriod, string ResidenceLength, string Unsubscribe_Ad, string Sacc_accountlock, string Dependant, string Memo, string Operator)
        {
            try
            {
                ClientInfo objClient = new ClientInfo();
                objClient.Title = Title;
                objClient.FirstName = FirstName;
                objClient.MiddleName = MiddleName;
                objClient.SurName = SurName;
                objClient.Citizenship = Citizenship;
                objClient.DateBirth = DateBirth;
                objClient.DriverLicense = DriverLicense;
                objClient.Mobile = Mobile;
                objClient.HomePhone = HomePhone;
                objClient.Email = Email;
                objClient.secondEmailAddress = secondEmailAddress;
                objClient.Street = Street;
                objClient.StreetNo = StreetNo;
                objClient.Suburb = Suburb;
                objClient.State = State;
                objClient.PostCode = PostCode;
                objClient.app_ResidentialStatus = app_ResidentialStatus;
                objClient.ResidencePeriod = ResidencePeriod;
                objClient.ResidenceLength = ResidenceLength;
                objClient.Unsubscribe_Ad = Unsubscribe_Ad;
                objClient.Sacc_accountlock = Sacc_accountlock;
                objClient.Dependant = Dependant;
                objClient.Memo = Memo;
                objClient.Operator = Operator;

                DataSet ds = objClient.AddClientDetail();
                string strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
        }
        public int PartiesContactAdd(int AppID, string Title, string FirstName, string MiddleName, string SurName, string Role, string Relationship, string DateBirth, string MobilePhone, string HomePhone, string WorkPhone, string FaxNumber, string secondEmailAddress, string Email2, string Street, string Suburb, string State, string PostCode, string PostalAddress, string IncomeType, string TypeofEntity, string BusinessName, string ABN, string NatureofBusiness, string Phone, string Address, string Employer, string Occupation, string JobPosition, string EmployerPhone, string ContactPerson, string WorkAddress, string KinsName, string KinsRelationship, string ContactNumber, string Notes)
        {
            int intReturnValue = 0;
            try
            {
                intReturnValue = ApplicationContactHandler.PartiesContactAdd(AppID, Title, FirstName, MiddleName, SurName, Role, Relationship, DateBirth, MobilePhone, HomePhone, WorkPhone, FaxNumber, secondEmailAddress, Email2, Street, Suburb, State, PostCode, PostalAddress, IncomeType, TypeofEntity, BusinessName, ABN, NatureofBusiness, Phone, Address, Employer, Occupation, JobPosition, EmployerPhone, ContactPerson, WorkAddress, KinsName, KinsRelationship, ContactNumber, Notes);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
            return intReturnValue;
        }
        public int ApplicationContactEdit(int ContactID, string Title, string FirstName, string MiddleName, string SurName, string Citizenship, string DateBirth,
            string DriverLicense, string Mobile, string HomePhone, string Email, string secondEmailAddress, string StreetNo, string Street, string Suburb,
            string State, string PostCode, string app_ResidentialStatus, string ResidencePeriod, string ResidenceLength, string Unsubscribe_Ad, string Sacc_accountlock,
            string Dependant, string Memo, string Operator)
        {
            int intReturnValue = 0;
            try
            {
                ClientInfo objClient = new ClientInfo();
                objClient.ContactID = ContactID;
                objClient.Title = Title;
                objClient.FirstName = FirstName;
                objClient.MiddleName = MiddleName;
                objClient.SurName = SurName;
                objClient.Citizenship = Citizenship;
                objClient.DateBirth = DateBirth;
                objClient.DriverLicense = DriverLicense;
                objClient.Mobile = Mobile;
                objClient.HomePhone = HomePhone;
                objClient.Email = Email;
                objClient.secondEmailAddress = secondEmailAddress;
                objClient.StreetNo = StreetNo;
                objClient.Street = Street;
                objClient.Suburb = Suburb;
                objClient.State = State;
                objClient.PostCode = PostCode;
                objClient.app_ResidentialStatus = app_ResidentialStatus;
                objClient.ResidencePeriod = ResidencePeriod;
                objClient.ResidenceLength = ResidenceLength;
                objClient.Unsubscribe_Ad = Unsubscribe_Ad;
                objClient.Sacc_accountlock = Sacc_accountlock;
                objClient.Dependant = Dependant;
                objClient.Memo = Memo;
                objClient.Operator = Operator;
                intReturnValue = objClient.UpdateClientDetail();

            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
            return intReturnValue;
        }
        public int PartiesContactEdit(int ContactID, string Title, string FirstName, string MiddleName, string SurName, string Role, string Relationship, string DateBirth, string MobilePhone, string HomePhone, string WorkPhone, string FaxNumber, string secondEmailAddress, string Email2, string Street, string Suburb, string State, string PostCode, string PostalAddress, string IncomeType, string TypeofEntity, string BusinessName, string ABN, string NatureofBusiness, string Phone, string Address, string Employer, string Occupation, string JobPosition, string EmployerPhone, string ContactPerson, string WorkAddress, string KinsName, string KinsRelationship, string ContactNumber, string Notes)
        {
            int intReturnValue = 0;
            try
            {
                intReturnValue = ApplicationContactHandler.PartiesContactEdit(ContactID, Title, FirstName, MiddleName, SurName, Role, Relationship, DateBirth, MobilePhone, HomePhone, WorkPhone, FaxNumber, secondEmailAddress, Email2, Street, Suburb, State, PostCode, PostalAddress, IncomeType, TypeofEntity, BusinessName, ABN, NatureofBusiness, Phone, Address, Employer, Occupation, JobPosition, EmployerPhone, ContactPerson, WorkAddress, KinsName, KinsRelationship, ContactNumber, Notes);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
            return intReturnValue;
        }

        public bool DeleteClient(int ContactID)
        {
            bool flag = false;
            try
            {
                flag = ApplicationContactHandler.deleteClient(ContactID);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
            return flag;
        }
        public int DeleteParties(int ContactID)
        {
            int intReturnValue = 0;
            try
            {
                intReturnValue = ApplicationContactHandler.DeleteParties(ContactID);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
            return intReturnValue;
        }


        //Update More Client Info:
        public int UpdateMoreClientInfo(int ContactID, string SelfEmpBusinessName, string SelfEmpABN, string SelfEmpNatureofBusiness, string SelfEmpPhone, string SelfEmpAddress, string KinsName, string KinsRelationship, string KinsContactNumber, string EmpEmployer, string EmpOccupation, string EmpJobPosition, string EmpEmployerPhone, string EmpContactPerson, string EmpWorkAddress)
        {
            int intReturnValue = 0;
            try
            {
                intReturnValue = ApplicationContactHandler.UpdateMoreClientInfo(ContactID, SelfEmpBusinessName, SelfEmpABN, SelfEmpNatureofBusiness, SelfEmpPhone, SelfEmpAddress, KinsName, KinsRelationship, KinsContactNumber, EmpEmployer, EmpOccupation, EmpJobPosition, EmpEmployerPhone, EmpContactPerson, EmpWorkAddress);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
            return intReturnValue;
        }

        #endregion
    }
}